package chances.wechat.controller;

import java.rmi.RemoteException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import chances.wechat.entity.StbInfo;
import chances.wechat.entity.WechatStbBind;
import chances.wechat.entity.WechatUser;
import chances.wechat.model.BindEvent;
import chances.wechat.msggw.context.BindContext;
import chances.wechat.msggw.resp.BaseResponse;
import chances.wechat.resp.ResultResponse;
import chances.wechat.service.WechatUserService;

@RestController
@RequestMapping(path = "/bind")
public class BindController extends UserAbstractController {
	
	@Autowired
	WechatUserService wechatUserService;
	
	Logger logger = LoggerFactory.getLogger("wxgw");
	
	Logger errorLogger = LoggerFactory.getLogger("error");
	
	@Value("${stb.limit:5}")
	private String stbLimit;
	
	/**
	 * 绑定用户机顶盒
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/device")
	public ResultResponse<String> bind(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) {
		String userId = request.getParameter("userId");
		String code = request.getParameter("code");
		WechatUser user = this.wechatUserService.getWechatUser(userId);
		if(user != null){
		    List<WechatStbBind> bindList = this.bindService.listBind(userId);
		    if(bindList.size() >= Integer.parseInt(stbLimit)){
		        return new ResultResponse<String>(501);
		    }
		    
		    return deviceBind(user, code);
		}else{
			return new ResultResponse<String>(404);
		}
	}
	
	/**
	 * 获取用户信息
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/user")
	public ResultResponse<WechatUser> getUserInfo(ModelMap model, HttpServletRequest request,
            HttpServletResponse response) {
        String userId = request.getParameter("userId");
        ResultResponse<WechatUser> result = new ResultResponse<WechatUser>();
        try{
            WechatUser user = this.wechatUserService.getWechatUser(userId);
            result.setStatus(200);
            result.setMessage("ok");
            if(user != null){
                result.setResult(user);
                return result;
            }
            return result;
        }catch(Exception e){
            errorLogger.info(e.getMessage(),e);
            result.setCode(500);
            result.setMessage(e.getMessage());
            return result;
        }    }

	
	
	
	
	
	/*private BindResponse getBindUrl(QrCodeInfo qrCodeInfo) {
		QrContext qrContext = new QrContext("getqrcode");
		qrContext.setIptvacct(qrCodeInfo.getStbNo());
		qrContext.setStbtype(qrCodeInfo.getScene());
		qrContext.setEpgversion(qrCodeInfo.getLocation());
		BindResponse bindResponse = null;
		try {
			bindResponse = bindService.bindStb(qrContext);
			bindService.getQrCode(qrContext);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return bindResponse;
	}*/
	
	
	/**
	 * 查询用户已绑定的机顶盒
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public ResultResponse<List<WechatStbBind>> list(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		ResultResponse<List<WechatStbBind>> result = new ResultResponse<List<WechatStbBind>>();
		try {
			List<WechatStbBind> bindList = this.bindService.listBind(userId);
			
			WechatUser user = this.wechatUserService.getWechatUser(userId);
			for(WechatStbBind bind:bindList){
			    if(bind.getStbNo().equals(user.getCurrentStbNo())){
			        bind.setMaster(true);
			    }
			}
			
			result.setStatus(SUCCESS);
			result.setResult(bindList);
		} catch (Throwable ex) {
			result.setStatus(DB_ERROR);
		}
		return result;
	}
	
	@RequestMapping("/unbind")
	public ResultResponse<String> unbind(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws RemoteException {

		String userId = request.getParameter("userId");
		String stbNo = request.getParameter("stbNo");
		ResultResponse<String> result = new ResultResponse<String>();
		WechatStbBind bind = this.bindService.query(userId, stbNo);
		try {
			if (bind != null) {
				this.bindService.delBind(bind.getBindId());
			}
			BaseResponse unbind = unbind(userId, bind);
			logStbUnbind(userId, stbNo, bind.getBindId() + "", unbind.getContent());
			result.setStatus(SUCCESS);
			result.setMessage(unbind.getContent());
		} catch (Throwable ex) {
			result.setStatus(SYS_ERROR);
		}
		
		StbInfo stbInfo = userRepository.findStbInfo(stbNo);
		BindEvent bindEvent = new BindEvent(userId, "", stbInfo, BindEvent.TYPE_UNBIND);
		try {
			this.applicationContext.publishEvent(bindEvent);
		} catch (Throwable e) {
			e.printStackTrace();
		}

		return result;
	}
	
	private BaseResponse unbind(String userId, WechatStbBind weixinBind) throws RemoteException {
		BindContext bindContext = new BindContext();
		bindContext.setCmd("unbind");
		bindContext.setAppacct(userId);
		bindContext.setBindid(weixinBind.getRoleName());
		BaseResponse bindResponse = this.bindService.unBind(bindContext);
		return bindResponse; 
	}
	
	/**
	 * 修改盒子备注
	 * @param desc
	 * @param bindId
	 * @return
	 */
	@PostMapping("/desc")
	public BaseResponse updateDesc(@RequestParam String desc,@RequestParam String bindId){
	    logger.info("desc:{},bindId:{}",desc,bindId);
	    BaseResponse result = new BaseResponse();
	    try {
            bindService.updateBindDesc(bindId,desc);
            result.setResCode("200");
            result.setResDesc("ok");
            return result;
        } catch (Exception e) {
            errorLogger.info(e.getMessage(),e);
            result.setResCode("500");
            result.setResDesc(e.getMessage());
            return result;            
        }
	    
	}
	
	
	/**
	 * 设置默认盒子
	 * @param bindId
	 * @param userId
	 * @return
	 */
	@PostMapping("/master")
	public BaseResponse setStbMaster(@RequestParam String stbNo,@RequestParam String userId){
	    logger.info("master:{},{}",stbNo,userId);
	    BaseResponse result = new BaseResponse();
	    try{
	        this.userRepository.updateUserMasterStbNo(stbNo, userId);	        
	        result.setResCode("200");
            result.setResDesc("ok");
            return result;
	    }catch(Exception e){
	        errorLogger.info(e.getMessage(),e);
            result.setResCode("500");
            result.setResDesc(e.getMessage());
            return result;
	    }
	}
	

/*

	

	*//**
	 * 创建用户绑定关系对象
	 * 
	 * @param request
	 * @return Bind
	 *//*
	private Bind createUserBind(HttpServletRequest request, String userId, String stbNo) {
		Bind bind = new Bind(userId, stbNo);
		bind.setStatus(Bind.ENABLE);
		bind.setNickname(RequestUtils.getParameter(request, "nickName", ""));
		bind.setRoleName(RequestUtils.getParameter(request, "roleName", ""));
		return bind;
	}
	
	*/
	
	
	/*
	private BaseResponse unbind(String userId, String bindId) throws RemoteException {
		BindContext bindContext = new BindContext();
		bindContext.setCmd("unbind");
		bindContext.setAppacct(userId);
		bindContext.setBindid(bindId);
		BaseResponse bindResponse = this.bindService.unBind(bindContext);
		return bindResponse;
	}*/

}
